package com.base.commons.tools.utils;

import cn.hutool.core.io.resource.ClassPathResource;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.AcroFields.FieldPosition;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;


/**
* @author 作者:carl
* @createDate 创建时间：2019年12月01日 上午9:32:04
*/
@Slf4j
public class PdfUtils {

    public static String pdfout(Map<String,Object> map,String templatePath ,String encodPath) {
        // 生成的新文件路径  
        String newPDFPath = FileUtil.rootPath()+ File.separator +"fbg-ods"+File.separator+ "pdfFile";
        //将pdf字节流输出到文件流
        File file = new File(newPDFPath);
        if (!file.exists()){
            file.mkdirs();
        }
        PdfReader reader = null;
        ByteArrayOutputStream bos = null;
        PdfStamper stamper = null;
        try {
            ClassPathResource resource = new ClassPathResource("pdf/arial.ttf");
            BaseFont FontChinese = BaseFont.createFont(resource.getUrl().toString(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
           // BaseFont FontChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font bf = new Font(FontChinese, 5F);
            // 读取pdf模板
            reader = new PdfReader(new ClassPathResource(templatePath).getStream());
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            /*书*/
            AcroFields form = stamper.getAcroFields();
            //遍历数据
            Map<String,Object> datemap = (Map<String,Object>)map.get("dateMap");
            // 添加所创建的字体
            form.addSubstitutionFont(FontChinese);
            for(String key : datemap.keySet()){
                String value = datemap.get(key).toString();
                form.setFieldProperty(value, "textfont", bf, null);
                form.setField(key,value);
            }
            //遍历条码字段
            Map<String,Object> barcodeFields=(Map<String, Object>) map.get("barcodeFields");
            for (Map.Entry<String, Object> entry : barcodeFields.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                // 获取属性的类型
                if(value != null && form.getField(key) != null){
                    //获取位置(左上右下)
                    FieldPosition fieldPosition = form.getFieldPositions(key).get(0);
                    //绘制条码
                    Barcode128 barcode128 = new Barcode128();
                    //字号
                    barcode128.setSize(10);
                    //条码高度
                    barcode128.setBarHeight(50);
                    //条码与数字间距
                    barcode128.setBaseline(15);
                    //条码值
                    barcode128.setCode(value.toString());
                    barcode128.setStartStopText(false);
                    barcode128.setExtended(true);
                    //绘制在第一页
                    PdfContentByte cb = stamper.getOverContent(1);
                    //生成条码图片
                    Image image128 = barcode128.createImageWithBarcode(cb, null, null);
                    //左边距(居中处理)
                    float marginLeft = (fieldPosition.position.getRight() - fieldPosition.position.getLeft() - image128.getWidth()) / 2;
                    //条码位置
                    image128.setAbsolutePosition(fieldPosition.position.getLeft() + marginLeft, fieldPosition.position.getBottom());
                    //加入条码
                    cb.addImage(image128);
                }
            }
            // 如果为false，生成的PDF文件可以编辑，如果为true，生成的PDF文件不可以编辑
            stamper.setFormFlattening(true);
            stamper.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try{
                if(reader!=null){
                    reader.close();
                }
                if(bos!=null){
                    bos.close();
                }
            }catch (Exception e1){
                e1.printStackTrace();
            }
        }
        return newPDFPath;
    }

    public static byte[] pdfoutBytes(Map<String,Object> map, String templatePath , String encodPath) {
        byte[] bytes = null;
        PdfReader reader = null;
        ByteArrayOutputStream bos = null;
        PdfStamper stamper = null;
        try {
            ClassPathResource resource = new ClassPathResource("pdf/arial.ttf");
            BaseFont FontChinese = BaseFont.createFont(resource.getUrl().toString(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            /*URL url = new File(encodPath).toURI().toURL();
            BaseFont FontChinese = BaseFont.createFont(url.toString(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);*/
            // BaseFont FontChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font bf = new Font(FontChinese, 5F);
            // 读取pdf模板
            reader = new PdfReader(new ClassPathResource(templatePath).getStream());
            /*FileInputStream templateStream = new FileInputStream(templatePath);
            reader = new PdfReader(templateStream);*/
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            /*书*/
            AcroFields form = stamper.getAcroFields();
            //遍历数据
            Map<String,Object> datemap = (Map<String,Object>)map.get("dateMap");
            // 添加所创建的字体
            form.addSubstitutionFont(FontChinese);
            for(String key : datemap.keySet()){
                String value = datemap.get(key).toString();
                form.setFieldProperty(value, "textfont", bf, null);
                form.setField(key,value);
            }
            //遍历条码字段
            Map<String,Object> barcodeFields=(Map<String, Object>) map.get("barcodeFields");
            for (Map.Entry<String, Object> entry : barcodeFields.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                // 获取属性的类型
                if(value != null && form.getField(key) != null){
                    //获取位置(左上右下)
                    FieldPosition fieldPosition = form.getFieldPositions(key).get(0);
                    //绘制条码
                    Barcode128 barcode128 = new Barcode128();
                    //字号
                    barcode128.setSize(10);
                    //条码高度
                    barcode128.setBarHeight(50);
                    //条码与数字间距
                    barcode128.setBaseline(15);
                    //条码值
                    barcode128.setCode(value.toString());
                    barcode128.setStartStopText(false);
                    barcode128.setExtended(true);
                    //绘制在第一页
                    PdfContentByte cb = stamper.getOverContent(1);
                    //生成条码图片
                    Image image128 = barcode128.createImageWithBarcode(cb, null, null);
                    //左边距(居中处理)
                    float marginLeft = (fieldPosition.position.getRight() - fieldPosition.position.getLeft() - image128.getWidth()) / 2;
                    //条码位置
                    image128.setAbsolutePosition(fieldPosition.position.getLeft() + marginLeft, fieldPosition.position.getBottom());
                    //加入条码
                    cb.addImage(image128);
                }
            }
            // 如果为false，生成的PDF文件可以编辑，如果为true，生成的PDF文件不可以编辑
            stamper.setFormFlattening(true);
            stamper.close();

            bytes = bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try{
                if(reader!=null){
                    reader.close();
                }
                if(bos!=null){
                    bos.close();
                }
            }catch (Exception e1){
                e1.printStackTrace();
            }
        }
        return bytes;
    }

    public static void main(String[] args) {
        //文本内容map
        Map<String,Object> map = new HashMap<String, Object>();

        map.put("code", "YKD_ES_ADA");
        map.put("to", "Lee Lei");
        map.put("address","153 Springs Lane");
        map.put("city", "Stalybridge");
        map.put("province", "United Kingdom");
        map.put("postal", "SK15 1HS");
        map.put("country", "UNITED KINGDOM");
        map.put("sku_3", "40-D4NGPBT50W220V*3");
        map.put("sku_1", "40-D4NGPBT50W220V*3");
        map.put("sku_2",  "40-D4NGPBT50W220V*3");
        //条形码map
        Map<String,Object> barcodeFields = new HashMap<String, Object>();
        barcodeFields.put("barCode","G1300-191128-0007-0");

        //组装map传过去
        Map<String,Object> o=new HashMap<String, Object>();
        o.put("dateMap",map);
        o.put("barcodeFields",barcodeFields);
        //执行
        //pdfout(o,"D:/miandan.pdf","D:/huawensongti.ttf");
        byte[] bytes = pdfoutBytes(o,"D:/opt/miandan.pdf","D:/opt/huawensongti.ttf");
        try {
            byte[] pngBytes = ImageUtil.pdf2Image(bytes);
            FileOutputStream pdfFis = new FileOutputStream("D:/opt/result.pdf");
            pdfFis.write(bytes);
            FileOutputStream pngFis = new FileOutputStream("D:/opt/result.png");
            pngFis.write(pngBytes);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
